package com.ts.notice;

import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@Component
public class ThreadDemo { // new ThreadDemo();

    private String name; // name安全吗？

    public void test2() {
        String name2;
    }

    public static void main(String[] args) {


        // 创建MyCallable对象
        Callable<Integer> myCallable = new MyCallable();

        //使用FutureTask来包装MyCallable对象
        FutureTask<Integer> ft = new FutureTask<Integer>(myCallable);

        //FutureTask对象作为Thread对象的target创建新的线程
        new Thread(ft).start();
        new Thread(ft).start();
        new Thread(ft).start();
        new Thread(ft).start();

        System.out.println("子线程启动完成..");

        try {
            //取得新创建的新线程中的call()方法返回的结果
            // get方法会阻塞，一直等待call()方法执行完后才会执行。
            System.out.println("等待子线程返回结果:");
            int sum = ft.get();
            System.out.println("sum = " + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class MyCallable implements Callable<Integer> {
    private int i = 0;

    @Override
    public Integer call() {
        int sum = 0;
        for (; i < 100; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sum += i;
        }
        return sum;
    }
}